package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.BindTeachplanMediaDto;
import com.xuecheng.commons.model.dto.TeachplanDto;
import com.xuecheng.commons.model.vo.MediaVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.domain.TeachplanMedia;
import com.xuecheng.content.mappers.TeachplanMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import com.xuecheng.content.service.TeachplanMediaService;
import com.xuecheng.content.service.TeachplanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.media.api.MediaClient;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-16
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private CourseBaseService courseBaseService;

    @Autowired
    private MediaClient mediaClient;

    @Autowired
    private TeachplanMediaService teachplanMediaService;

    //课程计划列表-树形结构
    @Override
    public ResponseResult treeNodes(Long courseId) {
        //根据课程id查询所有课程计划数据
        List<TeachplanVo> teachplanVos =  teachplanMapper.treeNodes(courseId);
        //查询出一级大纲
        TeachplanVo vo = teachplanVos.stream()
                .filter(teachplanVo -> teachplanVo.getGrade() == 1)
                .findFirst()
                .get();
        //查询二级大纲
        List<TeachplanVo> twos = teachplanVos.stream()
                .filter(teachplanVo -> teachplanVo.getGrade() == 2)
                .collect(Collectors.toList());
        vo.setTeachPlanTreeNodes(twos);
        //循环二级查询三级大纲
        for (TeachplanVo two : twos) {
            List<TeachplanVo> threes = teachplanVos.stream()
                    .filter(teachplanVo -> teachplanVo.getGrade() == 3 &&
                            teachplanVo.getParentid().equals(two.getId()))
                    .collect(Collectors.toList());
            two.setTeachPlanTreeNodes(threes);
        }
        //返回值
        return ResponseResult.okResult(vo);
    }

    //保存或者更新课程计划
    @Override
    public ResponseResult saveOrUpdatePlan(TeachplanDto dto) {
        //判断课程的状态
        Long courseId = dto.getCourseId();
        CourseBase courseBase = courseBaseService.getById(courseId);
        if (!courseBase.getAuditStatus().equals(CourseConstants.AUDIT_DISPAST_STATUS) &&
            !courseBase.getAuditStatus().equals(CourseConstants.AUDIT_UNPAST_STATUS)){
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //Parentid为空的时候,查一级大纲
        if (dto.getParentid()==null){
            //查询一级大纲
            LambdaQueryWrapper<Teachplan> qw = new LambdaQueryWrapper<>();
            qw.eq(Teachplan::getCourseId,courseId);
            qw.eq(Teachplan::getGrade,CourseConstants.FIRST_LEVEL);
            Teachplan teachplan = this.getOne(qw);
            dto.setParentid(teachplan.getId());
        }
        //转换对象
        Teachplan teachplan = BeanHelper.copyProperties(dto, Teachplan.class);
        //判断id  id不存在保存,存在修改
        Boolean b = false;
        if (teachplan.getId() ==null){
            //在保存课程大纲时，如果是三级大纲，需要对课程的章节数量+1
            Integer planNum = courseBase.getPlanNum();
            if (teachplan.getGrade()== CourseConstants.THIRD_LEVEL){
                courseBase.setPlanNum(planNum+1);
                courseBaseService.updateById(courseBase);
            }
           b =  this.save(teachplan);
        }else {
           b =  this.updateById(teachplan);
        }

        if (!b){
            throw  new BusinessException(ErrorCode.ERROR);
        }

        return ResponseResult.okResult();
    }

    //根据id删除课程计划(逻辑删除)
    @Override
    public ResponseResult deleteTeachplan(Long id) {
        //查询课程
        //查询大纲
        Teachplan teachplan = this.getById(id);
        CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
        //判断课程是否为可删除状态
        if (!courseBase.getAuditStatus().equals(CourseConstants.AUDIT_DISPAST_STATUS) &&
                !courseBase.getAuditStatus().equals(CourseConstants.AUDIT_UNPAST_STATUS)){
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //删除第三级的大纲并修改章节数
        if (teachplan.getGrade()==CourseConstants.THIRD_LEVEL){
            courseBase.setPlanNum(courseBase.getPlanNum()-1);
            courseBaseService.updateById(courseBase);
        }else if (teachplan.getGrade()==CourseConstants.SECEND_LEVEL){
            LambdaQueryWrapper<Teachplan> qw =new LambdaQueryWrapper<>();
            qw.eq(Teachplan::getParentid,teachplan.getId());
            int count = (int) this.count(qw);
            courseBase.setPlanNum(courseBase.getPlanNum()-count);
            courseBaseService.updateById(courseBase);
            //删除
            this.remove(qw);
        }else {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        boolean b = this.removeById(id);
        if (!b){
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        return ResponseResult.okResult();
    }

    //课程计划绑定媒资
    @Override
    public ResponseResult association(BindTeachplanMediaDto dto) {

        //判断基本参数
        if (dto.getMediaId()==null||dto.getTeachplanId()==null){
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        //判断课程状态
        Teachplan teachplan = this.getById(dto.getTeachplanId());
        CourseBase courseBase = courseBaseService.getById(teachplan.getCourseId());
        if (!courseBase.getAuditStatus().equals(CourseConstants.AUDIT_DISPAST_STATUS) &&
                !courseBase.getAuditStatus().equals(CourseConstants.AUDIT_UNPAST_STATUS)){
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //调用feign接口
        ResponseResult<MediaVo> result = mediaClient.findById(dto.getTeachplanId());
        MediaVo vo = result.getData();
        //查询媒资
        LambdaQueryWrapper<TeachplanMedia> qw  = new LambdaQueryWrapper<>();
        qw.eq(TeachplanMedia::getTeachplanId,dto.getTeachplanId());
        TeachplanMedia teachplanMedia = teachplanMediaService.getOne(qw);
        //不存在保存,存在更新
        if (teachplanMedia==null){
            teachplanMedia = new TeachplanMedia();
            teachplanMedia.setMediaId(dto.getMediaId());
            teachplanMedia.setTeachplanId(dto.getTeachplanId());
            teachplanMedia.setMediaFilename(vo.getFilename());
            teachplanMedia.setCourseId(teachplan.getCourseId());
            teachplanMedia.setCreateDate(new Date());
            teachplanMediaService.save(teachplanMedia);
        }else {
            teachplanMedia.setMediaId(vo.getId());
            teachplanMedia.setMediaFilename(vo.getFilename());
            teachplanMediaService.updateById(teachplanMedia);
        }
        return ResponseResult.okResult();
    }
}
